package com.lemon.smartsafety.ui.adapter.common;

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import com.baoyz.actionsheet.ActionSheet;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.app.IApplication;
import com.lemon.smartsafety.entity.common.EvidenceItemVo;
import com.lemon.smartsafety.entity.common.FileType;
import com.lemon.smartsafety.entity.common.UploadFileItem;
import com.lemon.smartsafety.utils.common.FileUtil;
import com.lemon.smartsafety.utils.common.ImageUtils;
import com.lemon.smartsafety.utils.common.LemonFileHelper;
import com.lemon.smartsafety.utils.common.LoggerHelper;
import com.lemon.smartsafety.utils.common.StringUtils;
import com.lemon.smartsafety.utils.task.FTaskItem;
import com.lemon.smartsafety.utils.task.FTaskQueue;

import java.util.ArrayList;
import java.util.List;

import cn.finalteam.galleryfinal.model.PhotoInfo;
import kale.adapter.LemonRcvAdapter;
import kale.adapter.item.AdapterItem;

/**
 * Created by Cooliean on 16/2/25.
 * 做一个通用的材料选择
 */
public class SelectEvidenceAdapter extends LemonRcvAdapter<EvidenceItemVo<PhotoInfo>> {
    private LoggerHelper loggerHelper = new LoggerHelper(SelectEvidenceAdapter.class);
    /**
     * 是否可以添加
     */
    private boolean mCanAdd = true;

    private int mPosition = 0;

    private String mWaterText = "";

    /**
     * 添加按钮
     */
    private EvidenceItemVo mAddVo;

    /**
     * 用于裁剪后回去的变量
     */
    private List<UploadFileItem> mCropItems = new ArrayList<>();
    /**
     * 记录已经删除的项目数组
     */
    private List<EvidenceItemVo<PhotoInfo>> mDeleteItems = new ArrayList<>();


    private String mAddEventTag = "";


    private ActionSheet.ActionSheetListener mActionSheetListener;

    public SelectEvidenceAdapter(@Nullable List<EvidenceItemVo<PhotoInfo>> data, boolean bAdd, String tag) {
        super(data);
        this.mCanAdd = bAdd;
        this.mAddEventTag = tag;
        setCanAdd(bAdd);
    }


    public boolean isCanAdd() {
        return mCanAdd;
    }

    /**
     * 设置是否可以添加附件
     *
     * @param canAdd
     */
    public void setCanAdd(boolean canAdd) {
        if (canAdd && !hasAddPlus()) {
            this.addItem(getAddPlusVo());
        } else {
            removeAddPlus();
        }
        this.mCanAdd = canAdd;
        notifyDataSetChanged();
    }


    /**
     * 是否有加号项
     *
     * @return
     */
    public boolean hasAddPlus() {
        boolean result = false;
        for (int i = 0; i < mDataList.size(); i++) {
            EvidenceItemVo vo = mDataList.get(i);
            if (RcvViewType.EvidenceViewType.TYPE_ADD == vo.getViewType()) {
                result = true;
                break;
            }
        }

        return result;
    }

    public void removeAddPlus() {
        for (int i = 0; i < mDataList.size(); i++) {
            EvidenceItemVo vo = mDataList.get(i);
            if (RcvViewType.EvidenceViewType.TYPE_ADD == vo.getViewType()) {
                mDataList.remove(vo);
                break;
            }
        }
    }


    public void removeAllNotPlus() {
        for (int i = 0; i < mDataList.size(); i++) {
            EvidenceItemVo vo = mDataList.get(i);
            if (RcvViewType.EvidenceViewType.TYPE_ADD != vo.getViewType()) {
                mDataList.remove(vo);
            }
        }
        notifyDataSetChanged();
    }


    public void removeAll() {
        mDataList.clear();
        notifyDataSetChanged();
    }


    @Override
    public long getItemId(int position) {
        mPosition = position;
        return super.getItemId(position);
    }

    /**
     * 已经排除掉加号
     *
     * @return
     */
    public List<EvidenceItemVo<PhotoInfo>> getItems() {
        List<EvidenceItemVo<PhotoInfo>> result = new ArrayList<>();
        if (this.mCanAdd) {
            for (int i = 0; i < mDataList.size() - 1; i++) {
                result.add(mDataList.get(i));
            }
        } else {
            for (int i = 0; i < mDataList.size(); i++) {
                result.add(mDataList.get(i));
            }
        }
        return result;
    }


    public void getUploadItems(final CropCallBack<List<UploadFileItem>> callBack) {
        if (callBack != null) {
            callBack.onStart();
        }
        mCropItems.clear();
        try {
            int size = mDataList.size();
            if (this.mCanAdd && size >= 1) {
                size = mDataList.size() - 1;
            }
            if (size == 0) {//一个文件都没有直接完成
                if (mDeleteItems.size() != 0) {
                    mCropItems.addAll(handlerDeleteItem());
                }
                callBack.onFinish(mCropItems);
                return;
            }
            FTaskQueue fTask = new FTaskQueue();

            for (int i = 0; i < size; i++) {
                final PhotoInfo photo = mDataList.get(i).getData();
                final String newPath = FileUtil.getFullPhotoPath(IApplication.context());
                final String oldPath = StringUtils.nullValue(photo.getPhotoPath());
                if (oldPath.length() == 0) {
                    continue;
                }


                FTaskItem<UploadFileItem> item = new FTaskItem<UploadFileItem>() {
                    @Override
                    public UploadFileItem getObject() {
                        UploadFileItem upload = null;
                        if (LemonFileHelper.isVoiceUrl(oldPath)) {
                            upload = new UploadFileItem();
                            upload.setOp(UploadFileItem.ADD);
                            String ext = FileUtil.getFileExt(oldPath).toLowerCase();
                            upload.setExt(ext);
                            upload.setType(FileType.VOICE.getValue());
                            upload.setBase64(ImageUtils.getImageBase64Code(oldPath));
                        } else if (LemonFileHelper.isImageUrl(oldPath)) {
                            boolean result = ImageUtils.decodeBitmap(oldPath, newPath, Constants.IMAGE_VIEW_WIDTH, Constants.IMAGE_VIEW_HEIGHT, getWaterText());
                            if (result) {
                                upload = new UploadFileItem();
                                upload.setOp(UploadFileItem.ADD);
                                String ext = FileUtil.getFileExt(newPath).toLowerCase();
                                upload.setExt(ext);
                                upload.setType(FileType.PHOTO.getValue());
                                upload.setBase64(ImageUtils.getImageBase64Code(newPath));

                            }
                        }
                        return upload;
                    }

                    @Override
                    public void update(UploadFileItem obj) {
                        if (null != obj) {
                            mCropItems.add(obj);
                        }
                        if (this.isLastItem() && mDeleteItems.size() != 0) {
                            mCropItems.addAll(handlerDeleteItem());
                        }
                        if (this.isLastItem() && callBack != null) {
                            callBack.onFinish(mCropItems);
                        }
                    }
                };
                if (i == (size - 1)) {
                    item.setLastItem(true);
                }
                fTask.execute(item);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private List<UploadFileItem> handlerDeleteItem() {
        List<UploadFileItem> result = new ArrayList<>();
        for (int i = 0; mDeleteItems != null && i < mDeleteItems.size(); i++) {
            EvidenceItemVo item = mDeleteItems.get(i);
            UploadFileItem upload = new UploadFileItem();
            upload.setOp(UploadFileItem.DEL);
            upload.setExt(item.getExt());
            upload.setFid(item.getFid());
            result.add(upload);
        }
        return result;
    }


    @Override
    public void addItems(int startPosition, List<EvidenceItemVo<PhotoInfo>> items) {
        super.addItems(startPosition, items);
    }

    public void addEvidenceItems(List<EvidenceItemVo<PhotoInfo>> items) {
        if (this.mCanAdd) {
            int position = mDataList.size() - 1;
            addItems(position, items);
        } else {
            addItems(0, items);
        }
        notifyDataSetChanged();
    }

    public void addEvidenceItem(EvidenceItemVo<PhotoInfo> item) {
        if (this.mCanAdd) {
            int position = mDataList.size() - 1;
            addItem(item, position);
        } else {
            addItem(item, 0);
        }
        notifyDataSetChanged();
    }

    public void removeEvidenceItems(int position) {
        EvidenceItemVo<PhotoInfo> item = this.remove(position);
        if (item != null && StringUtils.nullValue(item.getFid()).length() != 0) {//删除的时候有FileId的才进入已经删除的数组中
            mDeleteItems.add(item);
        }
    }

    public void removeEvidenceItems(EvidenceItemVo<PhotoInfo> data) {
        if (null == data) {
            return;
        }
        int position = mDataList.indexOf(data);
        removeEvidenceItems(position);
    }


    @Override
    public int getItemCount() {
        return super.getItemCount();
    }

    @Override
    public Object getItemType(EvidenceItemVo<PhotoInfo> vo) {
        return vo.getViewType();
    }


    public void setAddPlusEventTag(String tag) {
        this.mAddEventTag = StringUtils.nullValue(tag);
    }

    @NonNull
    @Override
    public AdapterItem createItem(Object type) {
        RcvViewType.EvidenceViewType myType = (RcvViewType.EvidenceViewType) type;

        if (RcvViewType.EvidenceViewType.TYPE_ADD == myType) {
            return new SelectEvidenceItemAdd(this.mAddEventTag);
        } else if (RcvViewType.EvidenceViewType.TYPE_PHOTO == myType) {
            return new SelectEvidencePhotoItem(this.mCanAdd);
        } else if (RcvViewType.EvidenceViewType.TYPE_VOICE == myType) {
            return new SelectEvidencePhotoItem(this.mCanAdd);
        }
        return new SectionHeadView();
    }

    public EvidenceItemVo getAddPlusVo() {
        if (mAddVo == null) {
            mAddVo = new EvidenceItemVo();
            mAddVo.setViewType(RcvViewType.EvidenceViewType.TYPE_ADD);
        }
        return mAddVo;
    }


    public void setActionSheetListener(ActionSheet.ActionSheetListener actionSheetListener) {
        mActionSheetListener = actionSheetListener;
    }


    public static interface CropCallBack<T> {
        public void onStart();

        public void onFinish(T data);
    }


    public void setWaterText(String mWaterText) {
        this.mWaterText = mWaterText;
    }


    public String getWaterText() {
        return StringUtils.nullValue(mWaterText);
    }
}
